package com.chensi.admin.shop.util;

import com.chensi.admin.shop.common.BaseErrorCode;
import com.chensi.admin.shop.common.Constants;
import com.chensi.admin.shop.common.JsonResult;
import com.chensi.admin.shop.exception.BaseException;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.ResponseEntity;

import java.util.Optional;

/**
 * @Author: si.chen
 * @Date: 2019/6/18 9:56
 */
public class ValidationUtil {

    /**
     * 检验非空
     */
    public static void isNull(Optional optional, String entity, String parameter, Object value) throws BaseException {
        if (!optional.isPresent()) {
            String msg = entity
                    + " 不存在 "
                    + "{ " + parameter + ":" + value.toString() + " }";
            throw new BaseException(BaseErrorCode.ITEM_NOT_FOUND.getCode(), msg, BaseErrorCode.ITEM_NOT_FOUND.getMessage());
        }
    }

    /**
     * 验证是否为邮箱
     */
    public static boolean isEmail(String string) {
        if (string == null) {
            return false;
        }
        String regEx1 = "^([a-z0-9A-Z]+[-|.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        return string.matches(regEx1);
    }

    /**
     * 检验密码强度:由数字和字母组成，并且要同时含有数字和字母，且长度要在8-16位之间
     */
    public static boolean isPassword(String string) {
        if (string == null) {
            return false;
        }
        String regEx1 = "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,16}$";
        return string.matches(regEx1);
    }

    /**
     * 解析ResponseEntity内容为data
     *
     * @param responseEntity 请求体
     * @return object
     * @throws BaseException 基本异常
     */
    public static Object validResponse(ResponseEntity<JsonResult> responseEntity) throws BaseException {
        JsonResult jsonResult = responseEntity.getBody();
        if (responseEntity.getStatusCodeValue() == Constants.HTTP_CODE && jsonResult != null) {
            if (StringUtils.equals(jsonResult.getCode(), Constants.CODE)) {
                return jsonResult.getData();
            } else {
                throw new BaseException(jsonResult.getCode(), jsonResult.getMessage());
            }
        } else {
            throw new BaseException(BaseErrorCode.UNKNOWN_EXCEPTION);
        }
    }
}
